<?php
/**
 * User: hjd-yao
 * Date: 2019/5/5
 * Time: 9:49
 */

namespace App\Http\Controllers\User;


use App\Helpers\Search;
use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Models\Manage\LogsAdminModel;
use App\Models\ManageAdminModel;
use App\Models\System\CurrencyModel;
use App\Models\User\AccountCorrectModel;
use App\Models\User\AccountFlowModel;
use DC\BonusCenter\Services\RegBonus;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;
use DC\UserCenter\Models\UserBaseModel;
use App\Models\Bonus\BonusCountModel;
use App\Models\Bonus\BonusRecordModel;
use DC\BonusCenter\Services\ShoppingBonus;


class AccountController extends BackendController
{
    /**
     * @title 账户校正
     * @param Request $request
     * @return SelfResponse|View
     */
    public function correctAccount(Request $request)
    {
        if($request->isMethod('post')){
            $currency = CurrencyModel::where('status',1)->pluck('name')->toArray();
            $validatedData = $request->validate([
                'user_number' => ['required','text_rule'],
                'correct_number' => 'required|numeric',
                'account' => ['required',Rule::in($currency)],
                'correct_type' => ['required',Rule::in([0,1])],
            ],[
                'required'=>':attribute不能为空',
                'numeric'=>':attribute只能为数值',
                'in'=>':attribute不是允许的值',
                'exists'=>':attribute不存在',
                'text_rule'=>':attribute不存在',
            ],[
                'user_number'=>'会员账号',
                'correct_number'=>'校正数量',
                'account'=>'校正账户',
                'correct_type'=>'校正方式'
            ]);
            $user_id = UserBaseModel::where('user_number',$validatedData['user_number'])->value('member_id');
            if(!$user_id){
                return SelfResponse::error('会员不存在!');
            }
            $field = $validatedData['account'];
            $money = abs($validatedData['correct_number']);
            if(!Schema::hasColumn('users_wallet',$field)){
                return SelfResponse::error('账户不存在!');
            }
            if($validatedData['correct_type']==1){
                $res = UserWalletModel::where('member_id',$user_id)->increment($field,$money);
                $type_msg = '增加';
            }else{
                $res = UserWalletModel::where('member_id',$user_id)->decrement($field,$money);
                $type_msg = '扣除';
            }
            if(!$res){
                return SelfResponse::error($type_msg.get_currency()[$field].'失败!');
            }
            AccountCorrectModel::init()->createRecord($user_id,$money,$field,$validatedData['correct_type']);
            $remark = $type_msg.$money.get_currency()[$field];
            LogsAdminModel::init()->setOptTitle('校正账户')->setRemark($remark)
                ->setOptData([
                    'user_id'=>$user_id,
                    'user_number'=>$validatedData['user_number'],
                    'field'=>$field,
                    'inout'=>$validatedData['correct_type'],
                    'money'=>$money
                ])->recording();

            return SelfResponse::success($type_msg.get_currency()[$field].'成功!');
        }else{
            $user_number = $request->get('user');
            return view('backend::account.correct_account',[
                'page_title'=>'校正账户',
                'user_number'=>$user_number,
                'currency'=>get_currency()
            ]);
        }
    }

    /**
     * @title 财务流水
     * @param Request $request
     * @return View
     */
    public function accountFlow(Request $request)
    {

        $search = Search::make($request)->bindModel(AccountFlowModel::with(['target' => function ($query) {
            $query->select(['member_id', 'user_number', 'real_name', 'user_phone']);
        }], ['relate' => function ($query) {
            $query->select(['member_id', 'user_number', 'real_name', 'user_phone']);
        }])->has('target'))
            ->input('target', '账号/姓名/手机号', '', ['field' => 'target_uid'])
            ->time('created_at', '创建时间')
            ->select('change_type', '类型', format_option([-100 => '全部'] + get_change()))
            ->select('money_type', '币种', format_option([-100 => '全部'] + get_currency('id')))
            ->bindSearchData()
            ->relationModel(['target' => function ($value) {
                return UserBaseModel::where('user_number', $value)
                    ->orWhere('real_name', $value)->orWhere('user_phone', $value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->where('status', 1)->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::account.account_flow', [
            'page_title' => '财务流水',
            'list' => $list,
            'search' => $search,
        ]);
    }


    /**
     * @title 校正明细
     * @param Request $request
     * @return View
     */
    public function correctFlow(Request $request)
    {

        $search = Search::make($request)->bindModel(new AccountCorrectModel())
            ->input('target','账号/姓名/手机号','',['field'=>'target_uid'])
            ->time('created_at','时间')
            ->select('money_type','币种',format_option([-100=>'全部']+get_currency('id')))
            ->bindSearchData()
            ->relationModel(['target'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);
        $model = $search->where()->where('status',1);

        $list = $model->with(['target'=>function($query){
            $query->select(['member_id','user_number','real_name','user_phone']);
        }])->has('target')->whereIn('operator_id',ManageAdminModel::init()->getChildren())->paginate($this->getPerPageNum());

        $count = $this->statsCorrect($model);

        return view('backend::account.correct_flow',[
            'page_title'=>'校正明显',
            'list'=>$list,
            'search'=>$search,
            'count'=>$count
        ]);
    }

    private function statsCorrect($model)
    {
       return $model->selectRaw('`inout`,sum(if(money_type=1,money,0)) as money1,sum(if(money_type=2,money,0)) as money2,sum(if(money_type=3,money,0)) as money3')
            ->groupBy('inout')->get()->toArray();
    }


    /**
     * @title 奖金统计
     * @param Request $request
     * @return View
     */

    public function bonusCount(Request $request)
    {

        $search = Search::make($request)->bindModel(BonusCountModel::with(['target'=>function($query){
            $query->select(['member_id','user_number','real_name','user_phone']);
        }])->has('target'))
            ->input('target','账号/姓名/手机号','',['field'=>'target_uid'])
            ->time('created_at','创建时间')
            ->bindSearchData()
            ->relationModel(['target'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::bonus.bonus_count',[
            'page_title'=>'奖金统计',
            'list'=>$list,
            'search'=>$search,
        ]);
    }


    /**
     * @title 奖金流水
     * @param Request $request
     * @return View
     */
    public function bonusRecord(Request $request)
    {
        $change_type=['42'=>'销售奖励'];
        $search = Search::make($request)->bindModel(BonusRecordModel::with(['target'=>function($query){
            $query->select(['member_id','user_number','real_name','user_phone']);
        }],['relate'=>function($query){
            $query->select(['member_id','user_number','real_name','user_phone']);
        }])->has('target'))
            ->input('target','账号/姓名/手机号','',['field'=>'target_uid'])
            ->time('created_at','创建时间')
            ->select('bonus_type','类型',format_option([-100=>'全部']+$change_type))
            ->bindSearchData()
            ->relationModel(['target'=>function($value){
                return UserBaseModel::where('user_number',$value)
                    ->orWhere('real_name',$value)->orWhere('user_phone',$value)->pluck('member_id')->toArray();
            }]);

        $list = $search->where()->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::bonus.bonus_record',[
            'page_title'=>'财务流水',
            'list'=>$list,
            'search'=>$search,
        ]);
    }

    /**
     * @title 合伙人月分红
     * @param Request $request
     * @return View
     */

    public function MonthAward(Request $request){
        if($request->isMethod('post')){

            $money = $request->input('money');

            if($money <=0 || !is_numeric($money)){
                return SelfResponse::error('请输入正确的分红金额');
            }

            $this->award($money);

            return SelfResponse::success('合伙人分红发放成功，请前往核对','b_Account_bonusCount');
        }
    }

    private function award($money)
    {
        $group=BonusRecordModel::max('group');
        if(!$group) {
            $group=1;
        }else{
            $group =$group+1;
        }
        RegBonus::make()->setGroup($group)->bonusMonthAward($money);
    }


    /**
     * @title 测试 全球分红 股东分红
     * @param Request $request
     * @return View
     */

    public function TestAward(Request $request){

        $type = $request->input('type');
        $reg_bonus = new RegBonus();
        if($type == 1){
            $reg_bonus->global_partnership('test');
        }else{
            $reg_bonus->bonusShareholderAward('test');
        }

        return SelfResponse::success('合伙人分红发放成功，请前往核对','b_Account_bonusRecord');

    }
}